import {
    pathToBase64,
    base64ToPath
} from './image-tool.js';
import store from "./store.js";

"use strict";
const request = function(url, data = {}, method = "GET", showLoading = true, contentType = 'application/json') {
    if (showLoading) {
        uni.showLoading({
            title: "请求中"
        })
    }
    const userId = store.state.userInfo != undefined ? store.state.userInfo.userId : ''
    return new Promise(function(resolve, reject) {
        uni.request({
            url: url,
            data: data,
            dataType: "json",
            method: method,
            header: {
                'content-type': contentType,
                'uid': userId
            },
            success: (res) => {
                // console.log(res)
                resolve(res.data);
            },
            fail: (res) => {
                reject(res)
            },
            complete: (res) => {
                if (showLoading) {
                    uni.hideLoading()
                }
            }
        })
    })
};

const autoLogin = function(ctx, onLogin) {
    // 请求登录（获取code）
    // #ifndef APP-PLUS
    uni.login({
        success: (res) => {
            let data = {
                code: res.code,
            };
            let url = null;
            // #ifdef MP-WEIXIN
            url = ctx.$api.ActionLogin;
            // #endif
            // #ifdef MP-ALIPAY
            url = ctx.$api.AliLogin;
            // #endif
            ctx.$request(url, data).then((res) => {
                console.log("登录", res.data.userId);
                uni.setStorageSync("userId", res.data.userId);
                if (res.returnCode == "SUCCESS") {
                    ctx.$store.state.userInfo = res.data;
                    //测试
                    // ctx.$store.state.userInfo.userId = '16068331633064321245'
                    // ctx.$store.state.userInfo.userId = 13600//上货ID

                    // ctx.openMsg()
                    // ctx.$store.state.role = res.data.courier ? 2 : 1;	// 设定角色
                    try {
                        if (typeof(onLogin) == 'function') {
                            onLogin();
                        }
                    } catch (e) {
                        console.log(e);
                    }
                } else if (res.returnCode == "FAIL") {
                    console.log("登录失败");
                    uni.showToast({
                        title: "登录失败",
                        icon: "none",
                    });
                }

                if (!ctx.$store.state.userInfo.phone
                    || !ctx.$store.state.userInfo.phone.trim()) {
                    console.log('new account');
                    setTimeout(function() {
                        uni.navigateTo({
                           url:'/subpackages/login/login'
                        })
                    }, 2000);
                }
            });
        },
        complete: (res) => {},
    });
    // #endif
};

// 判断是否为第一次登录
const checkLogin = function(ctx, onLogin) {
    let userInfo = ctx.$store.state.userInfo;
    if (!userInfo || !userInfo.phone || userInfo.phone == '') {
        autoLogin(ctx, onLogin);
    } else if (typeof(onLogin) == 'function') {
        onLogin();
    }
};

const extractUri = function(ctx, uri) {
    let parts = uri.split("?", 2);
    console.log("参数:" + parts);
    
    if (!parts || parts.length < 2) {
        console.log("empty params");
        return;
    }
    
    // 重置参数，避免上一次扫码的影响
    ctx.$store.state.deviceId = null;
    delete ctx.$store.state.doorIndex;
    
    let params = parts[1].split("&");
    for (let i in params) {
        let parts = params[i].split("=");
        if (!parts || parts.length < 2) {
            continue;
        }
        ctx.$store.state[parts[0]] = parts[1];
    }
    console.log("deviceId:" + ctx.$store.state.deviceId);
    console.log("doorIndex:" + ctx.$store.state.doorIndex);
}

const extractParams = function(ctx, query) {
    if (!query) {
        return;
    }

    let uri = "";
    if (query.qrCode) {
        // 支付宝获取二维码带参设备id
        uri = query.qrCode;
        console.log("支付宝 获取二维码:" + uri);
    } else if (query.q) {
        uri = decodeURIComponent(query.q);
        console.log("微信 获取二维码:" + uri);
    } else {
        return;
    }

    extractUri(ctx, uri)
}

// 获取指定长度的随机字符串
const radomString = function(length) {
    let data = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J",
        "K",
        "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "a", "b", "c", "d", "e", "f",
        "g", "h",
        "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"
    ];
    let result = "";
    for (let i = 0; i < length; i++) {
        let r = Math.floor(Math.random() * 62); //取得0-62间的随机数，目的是以此当下标取数组data里的值！
        result += data[r]; //输出20次随机数的同时，让rrr加20次，就是20位的随机字符串了。
    }
    return result;
};

const formatTime = time => {
    let d = new Date(time)
    const year = d.getFullYear()
    const month = d.getMonth() + 1
    const day = d.getDate()
    const hour = d.getHours()
    const minute = d.getMinutes()
    const second = d.getSeconds()

    return [year, month, day].map(formatNumber).join('-') + ' ' + [hour, minute, second].map(formatNumber).join(':')
};

const formatNumber = n => {
    n = n.toString()
    return n[1] ? n : '0' + n
};

function encodeUtf8(text) {
    const code = encodeURIComponent(text);
    const bytes = [];
    for (let i = 0; i < code.length; i++) {
        const c = code.charAt(i);
        if (c === '%') {
            const hex = code.charAt(i + 1) + code.charAt(i + 2);
            const hexVal = parseInt(hex, 16);
            bytes.push(hexVal);
            i += 2;
        } else bytes.push(c.charCodeAt(0));
    }
    return bytes;
};


export default {
    request: request,
    autoLogin: autoLogin,
    checkLogin: checkLogin,
    extractUri: extractUri,
    extractParams: extractParams,
    radomString: radomString,
    formatTime: formatTime,
    encodeUtf8: encodeUtf8,
    pathToBase64,
    base64ToPath,
};